//
//  UserAccount.swift
//  sinaWeibo
//
//  Created by liii on 16/7/10.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

private let userTokenKey = "userTokenKey"

class UserAccount: NSObject {

    var access_token: String?
    var uid: String?
    
    // access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    // token的过期日期
    var expires_date: NSDate?
    
    var name: String?
    var avatar_large: String? {
        didSet {
            // 在内存中
            headImageURL = NSURL(string: avatar_large ?? "")
        }
    }
    
    // 头像URL
    var headImageURL: NSURL?
    /**
    计算性属性(消耗cpu)
    var headImageURL: NSURL? {
        return NSURL(string: avatar_large ?? "")
    }
    */
    
    // 计算型属性
    var userLogin: Bool {
        return access_token != nil
    }
    
    /** 
    单例的设计
        1, static 保持静态
        2, let 保证唯一
        3, 私有化构造方法, 保证对象唯一
    */
    static let sharedUserAccount = UserAccount()
    
    // 构造方法,用于打印
    override private init() {
        super.init()
        loadUserInfo()
    }
    
    /// 重写description方法,用于打印成员变量
    override var description: String {
        let keys = ["access_token", "expires_in", "uid", "name", "avatar_large", "expires_date"]
        let data = self.dictionaryWithValuesForKeys(keys)
        return data.description
    }
}

// 业务逻辑相关处理
extension UserAccount {

    // 保存用户数据
    func saveUserInfo(dict: [String: AnyObject]) {
        
        // 字典转模型
        self.setValuesForKeysWithDictionary(dict)
        
        // 取出accessToken相关数据
        let tokenKeys = ["access_token", "expires_in", "uid", "name", "avatar_large", "expires_date"]
        let tokenValues = self.dictionaryWithValuesForKeys(tokenKeys)
        
        // 存储用户数据(偏好设置)
        userDefaults.setValue(tokenValues, forKey: userTokenKey)
        userDefaults.synchronize()
    }
    
    // 读取用户数据
    func loadUserInfo() {
        
        // 从沙盒取出的用户数据,为AnyObject类型, 强转成[String: AnyObject]类型的字典
        guard let userInfoDict = userDefaults.objectForKey(userTokenKey) as? [String: AnyObject] else {
            return
        }
        // 转换成模型数据
        self.setValuesForKeysWithDictionary(userInfoDict)
        
        print(self)
        
        // 判断token是否过期
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("token未过期")
        } else {
            print("token已过期")
            // token, 为空, 表示用户未登陆; 不为空, 表示用户已登录
            self.access_token = nil
        }
    }
    
    // 忽略不匹配 key
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        return
    }
}

/**
* 网络请求相关
*/
extension UserAccount {
    
    // 请求accessToken
    func loadAccessTokenRequest(code: String, completed: (isSuccess: Bool) -> ()) {
        
        // 拼接参数
        let afn = AFHTTPSessionManager()
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        
        // 发送POST请求
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        afn.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            // 获取token, 过滤掉请求数据失败的情况, 并将AnyObject转换成NSDictionary
            guard let dict = result as? [String : AnyObject] else {
                //失败的情况
                completed(isSuccess: false)
                return
            }
            // 请求用户数据
            self.loadUserInfo(dict, completed: completed)
            
            }) { (_, error) -> Void in
                completed(isSuccess: false)
                // 打印错误信息
                print(error)
        }
    }
    
    // 请求用户数据
    func loadUserInfo(dict: [String: AnyObject], completed: (isSuccess: Bool) -> ()) {
        
        let accessToken = dict["access_token"] as! String
        let uid = dict["uid"] as! String
        
        let afn = AFHTTPSessionManager()
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token" : accessToken, "uid" : uid]
        
        afn.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            // 过滤数据错误
            guard var userInfoDict = result as? [String : AnyObject] else {
                // 失败的回调
                completed(isSuccess: false)
                return
            }
            // 把access_token数据合并到用户字典里
            for (k, v) in dict {
                userInfoDict[k] = v
            }
            // 保存用户数据(* 注意沙盒不能存空)
            UserAccount.sharedUserAccount.saveUserInfo(userInfoDict)
            // 获取用户数据成功
            completed(isSuccess: true)
            
            }) { (_, error) -> Void in
                // 失败的回调
                completed(isSuccess: false)
                print(error)
        }
    }
}
